package touhou.game;

import gameframework.game.MoveBlocker;

import java.awt.Canvas;
import java.awt.geom.Point2D;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import touhou.base.Entity;
import touhou.base.Movable;
import touhou.base.Overlappable;
import touhou.game.OverlapProcessor;
import touhou.game.MoveBlockerChecker;

/**
 * Implementation de GameShooterUniverse, ajout du commportement de tir
 */
public class GameUniverseShooterImpl implements GameShooterUniverse {
	private ConcurrentLinkedQueue<Entity> gameEntities = new ConcurrentLinkedQueue<Entity>();
	private OverlapProcessor overlapProcessor;
	private MoveBlockerChecker moveBlockerChecker;

	public Iterator<Entity> gameEntities() {
		return gameEntities.iterator();
	}

	public GameUniverseShooterImpl(MoveBlockerChecker obs, OverlapProcessor col, Canvas canvas) {
		overlapProcessor = col;
		moveBlockerChecker = obs;
	}

	public synchronized void addGameEntity(Entity gameEntity) {
		gameEntities.add(gameEntity);
		if (gameEntity instanceof Overlappable) {
			overlapProcessor.addOverlappable((Overlappable) gameEntity);
		}
		if (gameEntity instanceof MoveBlocker) {
			moveBlockerChecker.addMoveBlocker((MoveBlocker) gameEntity);
		}
	}

	public synchronized void removeGameEntity(Entity gameEntity) {
		gameEntities.remove(gameEntity);
		if (gameEntity instanceof Overlappable) {
			overlapProcessor.removeOverlappable((Overlappable) gameEntity);
		}
		if (gameEntity instanceof MoveBlocker) {
			moveBlockerChecker.removeMoveBlocker((MoveBlocker) gameEntity);
		}
	}

	public void allOneStepMoves() {
		for (Entity entity : gameEntities) {
			if (entity instanceof Movable) {
				Movable m = ((Movable) entity);
				if (entity instanceof Projectile) {
					Point2D p = m.getPosition();
					if (p.getX() < -6 || p.getY() < -6 || p.getX() > 442/*16*28 -6*/ || p.getY() > 490/*16*31 -6*/) {
						removeGameEntity(entity);
					} else {
						m.oneStepMove();
					}
				} else {
					m.oneStepMove();
				}
			}
		}
	}

	public void processAllOverlaps() {
		overlapProcessor.processOverlapsAll();
	}

	@Override
	public void allOneStepShoot() {
		for (Entity entity : gameEntities) {
			if (entity instanceof GameShooter) {
				((GameShooter) entity).shoot(this);
			}
		}
	}
}
